package com.example.yxweather.ui.home


import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import com.example.yxweather.WeatherGlobal
import com.example.yxweather.base.BaseBindingFragment
import com.example.yxweather.databinding.FragmentHomeBinding
import com.example.yxweather.ui.home.HomeInteractor
import com.example.yxweather.ui.home.HomePresenter
import com.example.yxweather.ui.home.HomeView
import com.qweather.sdk.response.weather.WeatherNowResponse


class HomeFragment : BaseBindingFragment<FragmentHomeBinding>(), HomeView {

    // 1. ----- 初始化homePresenter -----
    // 声明HomePresenter变量，使用可空类型，便于后续延迟初始化
    private var homePresenter: HomePresenter? = null

    override fun initView() {
        homePresenter = HomePresenter(this, HomeInteractor())
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    // 2. 根据城市, 经纬度获取天气数据
    override fun onResume() {
        super.onResume()

        if (binding.topBar.tvCityName.text.isEmpty()) {
            refreshLocationWeatherData(
                WeatherGlobal.getCityName(),       // 获取保存的城市名称
                WeatherGlobal.getLatitude(),      // 获取保存的纬度
                WeatherGlobal.getLongitude()      // 获取保存的经度
            )
        }
    }

    fun refreshLocationWeatherData(
        cityName: String,
        latitude: String,
        longitude: String
    ) {
        // 设置城市位置参数到Presenter层
        homePresenter?.setCityLocationParams(cityName, latitude, longitude)
        // 显示加载进度条
        showLoading()
        // 请求主要天气数据
        homePresenter?.requestMainWeatherData()
    }


    override fun initBinding(
        inflater: LayoutInflater,
        parent: ViewGroup?
    ): FragmentHomeBinding {
        return FragmentHomeBinding.inflate(inflater, parent, false)
    }


    override fun getMainWeatherDataSuccess(response: WeatherNowResponse) {
        Log.d("HomeFragment", response.now.text)
        binding.tvTitle.text = response.now.text
        hideLoading()
    }

    override fun getMainWeatherDataFailed(msg: String) {
        hideLoading()

    }

}